# -*- coding: utf-8 -*-
"""
# 使用了 [adjustText==1.3.0]，遵循其 [MIT] 许可证，原始代码来源：[https://github.com/Phlya/adjustText]
# 使用了 [matplotlib==3.7.4]，遵循其 [PSF] 许可证，原始代码来源：[https://matplotlib.org]
# 使用了 [numpy==1.24.4]，遵循其 [BSD-3-Clause] 许可证，原始代码来源：[https://www.numpy.org]
# 使用了 [pandas==2.0.3]，遵循其 [BSD 3-Clause License] 许可证，原始代码来源：[https://pandas.pydata.org]
"""
import sys
from pathlib import Path
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import pandas as pd
from adjustText import adjust_text
class PARA_CONFIG:
    CURRENT_DIR=Path(__file__).parent.resolve()
    KMEANS_PATH=CURRENT_DIR.parent.parent.resolve()/"03_kmeans"/"src"/"result"/"5_Kmeans_SK_01_kmeans_20251031_150848.xlsx"
    FCHECK_PATH=CURRENT_DIR.parent.parent.resolve()/"04_fcheck"/"src"/"result"/"6_F_check_SK_01_f_check_20251031_151220.xlsx"
    FUNC_PATH=CURRENT_DIR.parent.parent.resolve()/"about_file"
sys.path.append(str(PARA_CONFIG.FUNC_PATH))
import f_basic

def process_label_data(ax,label,df,topics,annotate_top=6):
    """Step 06-01: draw subplot of Kmeans cluster."""
    df_topic_p=(df.query("label==@label")[topics].drop(columns=["label"],errors='ignore'))
    series_topic_p_mean=df_topic_p.mean(skipna=True,axis=0)
    series_topic_p_mean=series_topic_p_mean[series_topic_p_mean>0.0]
    ax.clear()
    ax=series_topic_p_mean.plot(kind='line',marker='o',markersize=5,linestyle='-',linewidth=1.5,color='#1f77b4',alpha=0.8,ax=ax)
    texts=[]
    if not series_topic_p_mean.empty:
        top_values = series_topic_p_mean.nlargest(annotate_top)
        for i, (topic_name, value) in enumerate(top_values.items()):
            x_pos = series_topic_p_mean.index.get_loc(topic_name)
            y_pos = value
            text = ax.text(
                x_pos,
                y_pos,
                f"{topic_name}\n{value:.2f}",
                fontsize=12,
                fontweight='bold',
                color='#d62728',
                ha='center',
                va='bottom',
                alpha=0.55,
                bbox=dict(
                    boxstyle='round,pad=0.2',
                    alpha=0.9,
                    facecolor='#FFFFCC',
                    edgecolor='#d62728',
                    linewidth=1
                )
            )
            texts.append(text)
    adjust_text(
        texts,
        ax=ax,
        expand_points=(1.2, 1.2),
        expand_text=(1.2, 1.2),
        force_points=(0.1, 0.1),
        force_text=(0.2, 0.2),
        ensure_inside_axes=True,
        avoid_points=True,
        avoid_text=True,
        only_move={'points': 'y', 'text': 'xy'},
        precision=0.01
    )
    ax.text(x=0.3,
            y=-0.05,
            s=f"聚类{label}共{len(df_topic_p)}篇文献",
            fontsize=12,
            fontweight='bold',
            color='#d62728',
            ha='center',
            va='top',
            alpha=0.55,
            transform=ax.transAxes,
            bbox=dict(
                boxstyle='round,pad=0.1',
                alpha=0.9,
                facecolor='#FFFFFF',
                edgecolor='#FFFFFF',
                linewidth=1
            ))
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.grid(True, linestyle='--', alpha=0.3)

@f_basic.Timer
def draw_paralle_line(fp_k,fp_f):
    """Step 06: draw the means value of clusters."""
    df_k=pd.read_excel(fp_k)
    df_k.columns=["T#"+str(col) for col in df_k.columns]
    df_k=df_k.rename(columns={"T#label":"label"})
    df_f=pd.read_excel(fp_f)
    li_topics=df_f["Topic"].values.tolist()#get the significant topic list.
    li_info=['label']
    li_topics.extend(li_info)

    fig=plt.figure(figsize=(10,12))
    labels=sorted(df_k['label'].unique())
    
    len_labels=len(labels)
    rows=(len_labels+1)//2
    gs=gridspec.GridSpec(rows+1,2,hspace=0.3)#make grids.
    axes=[fig.add_subplot(gs[pos//2,pos%2]) for pos in range(len(labels))]

    for ax,label in zip(axes,labels):#draw the subplots.
        process_label_data(ax,label,df_k,li_topics)
    f_basic.save_figure(fig,prefix="7_Draw_each_cluster_SK")

@f_basic.Timer
def main_stream():
    """do draw."""
    draw_paralle_line(PARA_CONFIG.KMEANS_PATH,PARA_CONFIG.FCHECK_PATH)

if __name__=="__main__":
    main_stream()
    